import qs from 'querystring'
import { getCurWebsite } from '@/views/common'
import { getTpl } from '@/views/tpl'
import { http } from '@/utils/axios'

export default {
  methods: {
    cleanData (data) {
      if (Array.isArray(data)) {
        return data.map(e => {
          Object.keys(e).forEach(key => {
            if (e[key] && typeof e[key] === 'string') {
              e[key] = e[key].replace(/(<span[\s\w=']+>)/, '').replace('</span>', '')
            }
          })
          if (e.total) {
            e.total = this.cleanData(e.total)
          }
          if (e.data) {
            e.data = this.cleanData(e.data)
            if (e.total) {
              e.total.NAME0 = '总计'
              e.data.unshift(e.total)
            }
          }
          return e
        })
      }
      if (Object.prototype.toString.call(data) === '[object Object]') {
        Object.keys(data).forEach(key => {
          if (data[key] && typeof data[key] === 'string') {
            data[key] = data[key].replace(/(<span[\s\w=']+>)/, '').replace('</span>', '')
          }
        })
        return data
      }
      return []
    },
    getFirstItemData (item, index) {
      this.loading = true
      this.$set(this.accountList[index], 'statusText', '请求中...')
      this._getFirstItemData(item)
        .then(res => {
          const { data, message } = res
          if (data) {
            let { name, level } = item
            if (this.startDate && this.endDate) {
              name = this.startDate.substring(5) + '-' + this.endDate.substring(5) + '——' + name
            }
            const newData = this.cleanData(data).map(e => {
              return {
                ...e,
                fromLevel: level
              }
            })
            console.log('newData')
            console.log(newData)
            if (newData && newData.length) {
              const tplData = getTpl({ data: newData })
              this.sendToMainProcess(`${name}.html`, tplData)
            }
          }
          this.$set(this.accountList[index], 'statusText', message === 'success' ? '请求成功' : message)
        })
        .catch(e => {
          console.log(e)
          this.$set(this.accountList[index], 'statusText', e || '请求失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getAllFirstData (failList) {
      const list = failList || this.accountList
      if (!list || !list.length) {
        return
      }
      this.loading = true
      let tempSpace = []
      const len = list.length
      let index = 0
      const callback = () => {
        this.loading = false
        const allData = this.waitExportList
        const exportData = () => {
          if (allData.length === 0) {
            return this.$message.info('请求数据为空')
          }
          let name = this.accountList.map(e => e.name).join('、')
          if (this.startDate && this.endDate) {
            name = this.startDate.substring(5) + '-' + this.endDate.substring(5) + '——' + name
          }
          const tplData = getTpl({ data: allData })
          this.sendToMainProcess(`${name}.html`, tplData)
          this.waitExportList = []
          // this.errorList = []
        }

        this.checkExistErrorList(() => exportData())
      }

      console.log('list')
      console.log(list)
      for (let i = 0; i < len; i++) {
        const item = list[i]
        const { level } = item
        const itemIndex = this.accountList.findIndex(a => a.name === item.name)
        this.$set(this.accountList[itemIndex], 'statusText', '请求中...')
        this._getFirstItemData(item)
          .then(res => {
            const { data, message } = res
            tempSpace[i] = [...this.cleanData(data)].map(e => {
              return {
                ...e,
                fromLevel: level
              }
            })
            this.$set(this.accountList[itemIndex], 'statusText', message === 'success' ? '请求成功' : message)
          })
          .catch(e => {
            this.errorList.push(item)
            this.$set(this.accountList[itemIndex], 'statusText', e && typeof e === 'string' ? e : '请求失败')
          })
          .finally(() => {
            index = index + 1
            if (index === len) {
              // 过滤掉空的index
              tempSpace = tempSpace.filter(e => e)
              tempSpace.forEach(e => {
                this.waitExportList.push(...e)
              })
              callback()
              this.loading = false
            }
          })
      }
    },
    _getFirstItemData (item) {
      return new Promise((resolve, reject) => {
        const { name, psw, code, level } = item
        const children = this.getChilren(item.children)
        const { startDate, endDate } = this
        const baseUrl = getCurWebsite()
        // const baseUrl = 'http://176.113.69.25:3100'
        const pathUrl = baseUrl + '/users'
        // eslint-disable-next-line eqeqeq
        let url = pathUrl + (level == 1 ? '/loginone' : level == 2 ? '/logintwo' : '/loginthree')
        // eslint-disable-next-line eqeqeq
        if (level == 0) {
          url = baseUrl + '/crwon/loginone'
        }
        let data
        if (children && children.length) {
          data = qs.stringify({
            username: name,
            pwd: psw,
            safecode: code,
            date_start: startDate,
            date_end: endDate,
            children: children && children.length ? JSON.stringify(children) : ''
          })
        } else {
          data = qs.stringify({
            username: name,
            pwd: psw,
            safecode: code,
            date_start: startDate,
            date_end: endDate
          })
        }
        http({
          method: 'post',
          url,
          withCredentials: false,
          data
        }).then(res => {
          console.log('get report', res)
          if (this.checkSuccess(res)) {
            resolve(res.data)
          } else {
            reject(res && res.data && res.data.message)
          }
        }).catch(e => {
          console.error('Report Error: ', e)
          reject((e && e.data && e.data.message) || '系统报表繁忙，请稍后再试')
        })
      })
    }
  }
}
